import Layout from "@/layout/Index.vue";
import router from "@/router";
const modules = import.meta.glob("../views/**/**.vue")
// 添加动态路由
export const setRouterPackag = (list = []) => {
  const routers = getRoutes(JSON.parse(JSON.stringify(list)));
  if (routers && routers.length > 0) {
    for (let i = 0; i < routers.length; i++) {
      if (isRouter(routers[i])) {
        router.addRoute(routers[i]);
      }
    }
  }
  // 404页面
  const notPath = { path: "/:catchAll(.*)", redirect: "/404" };
  if (isRouter(notPath)) {
    router.addRoute(notPath); 
  }
};

// 处理获取到路由的参数
const getRoutes = (list) => {
  for (let i = 0; i < list.length; i++) {
    if (list[i].component === "Layout") {
      list[i].component = Layout;
    } else if (list[i].component) {
      list[i].component = modules[`../views${list[i].component}.vue`];
    }
    if (list[i].children && list[i].children.length > 0) {
      getRoutes(list[i].children)
    }
  }
  return list
};

// 判断路由是否有重复值
const isRouter = (item = {}) => {
  const routers = router.getRoutes();
  if (item && Object.keys(item).length > 0) {
    const index = routers.findIndex((x) => x.path === item.path);
    if (index !== -1) {
      return false;
    }
    return true;
  }
  return false;
};
